package com.cn.removewatermark.batchdownload;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.cn.removewatermark.domain.MyProgress;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;

/*
 * 下载视频的线程类型
 * */
public class DownloadThead implements Runnable {

    public static String date = "";
    public final static String path = Paths.get("RemoveWatermark").toAbsolutePath().toString().substring(0, Paths.get("RemoveWatermark").toAbsolutePath().toString().indexOf("RemoveWatermark"));

    @Override
    public void run() {
        while (true) {
            BufferedInputStream in = null;
            BufferedOutputStream out = null;
            String take = "";
            try {
                Thread.sleep(1000 + new Random().nextInt(4));
                take = Download.messageQueue.take();
                System.out.println("messageQueue==========="+Download.messageQueue.size());
                HttpResponse execute = HttpUtil.createGet(take).addHeaders(BatchDownload.header).execute();
                InputStream inputStream = execute.bodyStream();
                byte[] bytes = new byte[1024];
                in = new BufferedInputStream(inputStream);
                out = new BufferedOutputStream(new FileOutputStream(Paths.get(path + date) + "/" + UUID.randomUUID() + ".mp4"));
                URL url = new URL(take);
                URLConnection connection = url.openConnection();
                int len = 0;
                long total = 0;
                int currentPercentage = 0;
                long contentLength = connection.getContentLength();
                while ((len = in.read(bytes)) != -1) {
                    out.write(bytes, 0, len);
                    total += len;
                    int newPercentage = (int) (total * 100 / contentLength);
                    if (total <= contentLength) {
                        currentPercentage = newPercentage;
                        if (Objects.isNull(BatchDownload.getReplicaVariable(Thread.currentThread().getName()))) {
//                            System.out.println("设置MyProgress");
                            BatchDownload.add(Thread.currentThread().getName(), new MyProgress(0.0,false));
                        }
                        BatchDownload.getReplicaVariable(Thread.currentThread().getName()).setProgress((double) currentPercentage/100);
//                        System.out.print("\r下载进度：" + currentPercentage + "%");
                    }

//                    System.out.println("=============="+Thread.currentThread().getName());

                }
                //此次任务下载完成
                BatchDownload.getReplicaVariable(Thread.currentThread().getName()).setEnd(true);
            } catch (InterruptedException | IOException e) {
                throw new RuntimeException(e);
            } finally {
                BatchDownload.countDownLatch.countDown();
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

    }

}
